unit uUtils;

interface

uses
  Types, Graphics;

const
  TileSize = 32;
  PanelWidth = 6;
  ScrollPadding = 20; 
  
var
  Path: string = '';
  IsGrid: Boolean = False;
  IsEdit: Boolean = False;
  IsMove: Boolean = True;
  ScreenWidth: Integer;
  ScreenHeight: Integer;
  MapTop: Integer = 0;
  MapLeft: Integer = 0;

procedure BitmapFromTileset(Tile, Tileset: Graphics.TBitmap; Index, ATileSize: Integer);
procedure ScaleBmp(var ABitmap: Graphics.TBitmap; CX, CY: Integer);
function Rand(A, B: Integer): Integer;
function PointInRect(X, Y: Integer; RX, RY, RW, RH: Integer): Boolean;
function EqualPoints(P1, P2: TPoint; Tolerance: Byte = 0): Boolean;

implementation

uses SysUtils;

procedure BitmapFromTileset(Tile, Tileset: Graphics.TBitmap; Index, ATileSize: Integer);
var
  Col, Row, ColCount, RowCount : Integer;
begin
  if (Index < 0) then Index := 0;
  ColCount := Tileset.Width div ATileSize;
  RowCount := Tileset.Height div ATileSize;
  if (Index > (ColCount * RowCount) - 1) then
    Index := (ColCount * RowCount) - 1;
  Tile.Width := ATileSize;
  Tile.Height := ATileSize;
  Tile.PixelFormat := pf16bit;	
  Col := Index mod ColCount;
  Row := Index div ColCount;
  Tile.Canvas.CopyRect(Bounds(0, 0, ATileSize, ATileSize), Tileset.Canvas,
    Bounds(Col * ATileSize, Row * ATileSize, ATileSize, ATileSize));
end;

procedure ScaleBmp(var ABitmap: Graphics.TBitmap; CX, CY: Integer);
var
  B: Graphics.TBitmap;
begin
  B := Graphics.TBitmap.Create;
  try
    B.Width := CX;
    B.Height := CY;
    B.Canvas.StretchDraw(Rect(0, 0, CX, CY), ABitmap);
    ABitmap.Assign(B);  
  finally
    B.Free;
  end;
end;

function Rand(A, B: Integer): Integer;
begin
  Result := Round(Random(B - A + 1) + A);
end;

function PointInRect(X, Y: Integer; RX, RY, RW, RH: Integer): Boolean;
begin
  Result := (X > RX) and (X < RX + RW) and (Y > RY) and (Y < RY + RH);
end;

function EqualPoints(P1, P2: TPoint; Tolerance: Byte = 0): Boolean;
begin
  Result := (Abs(P1.X - P2.X) <= Tolerance) and (Abs(P1.Y - P2.Y) <= Tolerance);
end;

initialization
  Randomize;

finalization

end.

